import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'index.dart';

/// 登录页面视图
/// 
/// 水墨风格的登录界面，采用黑白灰色调和传统中国元素
/// 包含用户名密码表单、记住密码功能和动画效果
class LoginPage extends GetView<LoginController> {
  const LoginPage({super.key});

  // 主视图构建方法
  Widget _buildView() {
    return Center(
      child: SingleChildScrollView(
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 20),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20),
          ),
          child: _buildLoginForm(),
        ),
      ),
    );
  }

  /// 构建登录表单
  Widget _buildLoginForm() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 20),
      child: Form(
        key: controller.formKey,
        child: Column(
          children: [
            // 标题
            Padding(
              padding: const EdgeInsets.only(top: 20, bottom: 40),
              child: const Text(
                '登录',
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            
            // 手机号输入框
            _buildPhoneField(),
            const SizedBox(height: 10),
            
            // 验证码输入框（带发送验证码按钮）
            _buildCodeFieldWithButton(),
            const SizedBox(height: 10),
            
            // 协议勾选框
            _buildProtocolRow(),
            const SizedBox(height: 20),
            
            // 登录按钮
            _buildLoginButton(),
            
            // 错误信息显示
            if (controller.hasError.value) ...[
              const SizedBox(height: 16),
              _buildErrorMessage(),
            ],
          ],
        ),
      ),
    );
  }

  /// 构建手机号输入框
  Widget _buildPhoneField() {
    return TextField(
      controller: controller.phoneController,
      focusNode: controller.phoneFocusNode,
      onChanged: controller.onPhoneNumberChanged,
      keyboardType: TextInputType.phone,
      maxLength: 11,
      decoration: InputDecoration(
        hintText: '请输入手机号码',
        border: const UnderlineInputBorder(),
        prefixIcon: const Icon(Icons.phone_android),
        counterText: '', // 隐藏计数器
        errorText: controller.validationErrors.containsKey('phone') 
            ? controller.validationErrors['phone'] 
            : null,
      ),
    );
  }

  /// 构建验证码输入框（带发送验证码按钮）
  Widget _buildCodeFieldWithButton() {
    return Row(
      children: [
        Expanded(
          child: TextField(
            controller: controller.codeController,
            focusNode: controller.codeFocusNode,
            onChanged: controller.onVerificationCodeChanged,
            keyboardType: TextInputType.number,
            maxLength: 6,
            decoration: InputDecoration(
              hintText: '请输入手机短信验证码',
              border: const UnderlineInputBorder(),
              prefixIcon: const Icon(Icons.security),
              counterText: '', // 隐藏计数器
              errorText: controller.validationErrors.containsKey('code') 
                  ? controller.validationErrors['code'] 
                  : null,
            ),
          ),
        ),
        const SizedBox(width: 10),
        // 发送验证码按钮
        _buildSendCodeButton(),
      ],
    );
  }

  /// 构建发送验证码按钮
  Widget _buildSendCodeButton() {
    // 判断按钮是否可用
    final isEnabled = controller.phoneNumber.value.trim().isNotEmpty &&
        controller.isAgreeProtocol.value &&
        controller.smsCountdown.value == 0 &&
        !controller.isSendingSms.value;
    
    return SizedBox(
      width: 110,
      height: 40,
      child: ElevatedButton(
        onPressed: isEnabled ? controller.onSendCodeTap : null,
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFFCB5050).withOpacity(0.9),
          foregroundColor: Colors.white,
          disabledBackgroundColor: Colors.grey.shade300,
          disabledForegroundColor: Colors.grey.shade600,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 8),
        ),
        child: controller.isSendingSms.value
            ? const SizedBox(
                width: 16,
                height: 16,
                child: CircularProgressIndicator(
                  color: Colors.white,
                  strokeWidth: 2,
                ),
              )
            : Text(
                controller.smsCountdown.value > 0
                    ? '${controller.smsCountdown.value}s'
                    : '发送验证码',
                style: const TextStyle(fontSize: 12),
              ),
      ),
    );
  }

  /// 构建协议勾选行
  Widget _buildProtocolRow() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        SizedBox(
          width: 18,
          height: 18,
          child: Checkbox(
            value: controller.isAgreeProtocol.value,
            onChanged: (value) => controller.toggleAgreeProtocol(),
            shape: const CircleBorder(),
            activeColor: const Color(0xFFCB5050),
            side: const BorderSide(color: Colors.red, width: 1),
          ),
        ),
        const SizedBox(width: 6),
        Expanded(
          child: Wrap(
            crossAxisAlignment: WrapCrossAlignment.center,
            spacing: 2,
            children: [
              const Text(
                '勾选同意',
                style: TextStyle(fontSize: 12, color: Colors.black87),
              ),
              GestureDetector(
                onTap: controller.onUserManualTap,
                child: const Text(
                  '《用户手册》',
                  style: TextStyle(fontSize: 12, color: Colors.black87),
                ),
              ),
              const Text(
                '和',
                style: TextStyle(fontSize: 12, color: Colors.black87),
              ),
              GestureDetector(
                onTap: controller.onPrivacyPolicyTap,
                child: const Text(
                  '《隐私政策》',
                  style: TextStyle(fontSize: 12, color: Colors.black87),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建登录按钮
  Widget _buildLoginButton() {
    return SizedBox(
      width: double.infinity,
      height: 50,
      child: ElevatedButton(
        onPressed: controller.isLoading.value ? null : controller.onLoginTap,
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFFCB5050),
          foregroundColor: Colors.white,
          disabledBackgroundColor: Colors.grey.shade400,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(25),
          ),
        ),
        child: controller.isLoading.value
            ? const SizedBox(
                width: 20,
                height: 20,
                child: CircularProgressIndicator(
                  color: Colors.white,
                  strokeWidth: 2,
                ),
              )
            : const Text(
                '登录',
                style: TextStyle(fontSize: 18),
              ),
      ),
    );
  }

  /// 构建错误信息
  Widget _buildErrorMessage() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        color: Colors.red.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: Colors.red.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.error_outline,
            color: Colors.red.withOpacity(0.8),
            size: 16,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              controller.errorMessage.value,
              style: TextStyle(
                color: Colors.red.withOpacity(0.9),
                fontSize: 14,
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LoginController>(
      init: LoginController(),
      id: "login",
      builder: (_) {
        return Scaffold(
          backgroundColor: const Color(0xFFCB5050),
          resizeToAvoidBottomInset: false,
          extendBodyBehindAppBar: true,
          extendBody: true,
          appBar: AppBar(
            backgroundColor: Colors.transparent,
            elevation: 0,
            toolbarHeight: 0,
            systemOverlayStyle: const SystemUiOverlayStyle(
              statusBarColor: Colors.transparent,
              statusBarIconBrightness: Brightness.light,
              statusBarBrightness: Brightness.dark,
            ),
          ),
          body: SafeArea(
            top: false,
            child: _buildView(),
          ),
        );
      },
    );
  }
}
